﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace QuTouTiaoAssist.Util
{
    class HttpUtil
    {
        public static WebProxy Proxy;

        public static HttpWebResponse GetResponse(string requestUrl, HttpMethod method, string postData)
        {
            System.Net.HttpWebRequest req = HttpWebRequest.Create(requestUrl) as HttpWebRequest;
            req.Method = method.ToString(); 
            req.ContentType = "application/x-www-form-urlencoded";
            if (Proxy != null)
            {
                req.Proxy = Proxy;
            }
            if (method == HttpMethod.POST)
            {
                byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(postData);
                req.ContentLength = dataBytes.Length;
                using (var stream = req.GetRequestStream())
                {
                    stream.Write(dataBytes,0,dataBytes.Length);
                }
            }

            System.Net.HttpWebResponse resp = req.GetResponse() as HttpWebResponse;

            return resp;
        }

        public static string GetResponseString(string requestUrl, HttpMethod method, string postData)
        {
            using (var stream = GetResponse(requestUrl,method, postData).GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
}
